//
//  BookTableViewController.swift
//  ZTC_Final
//
//  Created by xy Man on 2022/5/25.
//

import UIKit

class BookTableViewController: UITableViewController {

    var sqlite:SQLiteManager?
    var query:[[String : AnyObject]]?
    var tmp = ["不可能存在的类型"]
    var realindex:Int = 0
    var username:String?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let xib = UINib(nibName: "BookTableViewCell", bundle: nil)
        tableView.register(xib, forCellReuseIdentifier: "BookCatogory")
        tableView.rowHeight = 199
        sqlite = SQLiteManager.sharedInstance
        
        if !sqlite!.openDB(){return}
        query = sqlite!.execQuerySQL(sql: "SELECT * FROM book")
        sqlite!.closeDB()
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections

        for i in query!{
            tmp.append(i["kind"] as! String)
        }
        let numOfSections = Set(tmp).count - 1
        return numOfSections
//        return 1
        
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
//        let tmpsql = "SELECT * FROM book GROUP BY kind;"
//        let tempsqlite = SQLiteManager.sharedInstance
//        tempsqlite.openDB()
//        let tmpquery = tempsqlite.execQuerySQL(sql: tmpsql)
//        tempsqlite.closeDB()
//
//        for i in tmpquery!{
//            print("\(String(describing: i["kind"]))")
//            for j in i{
//                print(j)
//            }
//        }
//
//        let a = tmpquery![section].count
//        return a
        return 10
        
    }

    func mapRealIndex(section:Int, row:Int)->Int{
        if section == 0{
            return row
        }else if section == 1{
            return row + 20
        }else{
            return row + 10
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        realindex = mapRealIndex(section: indexPath.section, row: indexPath.row)
        performSegue(withIdentifier: "cato2detail", sender: nil)
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            let tmpsql = "SELECT * FROM book GROUP BY kind;"
            let tempsqlite = SQLiteManager.sharedInstance
            tempsqlite.openDB()
            let tmpquery = tempsqlite.execQuerySQL(sql: tmpsql)
            tempsqlite.closeDB()
            return tmpquery![section]["kind"] as? String
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BookCatogory", for: indexPath) as! BookTableViewCell

        // Configure the cell...
        realindex = mapRealIndex(section: indexPath.section, row: indexPath.row)
        cell.bookName.text = query![realindex]["title"]as?String
        cell.bookPrice.text = String(format: "%.2f", query![realindex]["price"] as! Double)+"元/本"
        // 从网络上获取图片
        let pic_path:String = query![realindex]["pic_path"]as! String
        let nsurl = NSURL(string: pic_path)
        let nsd = NSData(contentsOf: nsurl! as URL)
        let myImage = UIImage(data: nsd! as Data)
        cell.bookImage.image = myImage
        // cell.bookImage.image = UIImage(contentsOfFile: pic_path)
        // 已购数量
        cell.hasBuyNum.text = "\(getHasBuy(username: username!, bookname: query![realindex]["title"] as! String))本"
        return cell
    }
    
    func getHasBuy(username:String, bookname:String)->Int{
        let sqlite = SQLiteManager.sharedInstance
        if !sqlite.openDB(){return -1}
        let tmpsql = "SELECT number FROM shopping WHERE username = '\(username)' AND bookname = '\(bookname)';"
        let queryres = sqlite.execQuerySQL(sql: tmpsql)
        sqlite.closeDB()
        if queryres!.count == 0{
            return 0
        }else{
            return queryres![0]["number"] as! Int
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        let detail = segue.destination as! detailViewController
        detail.username = username
        detail.name = query![realindex]["title"] as! String
        detail.price = "\(query![realindex]["price"]!)"
        detail.pic_path = query![realindex]["pic_path"] as! String
        detail.author = query![realindex]["author"] as! String
        detail.ddescription = query![realindex]["description"] as! String
        detail.ISBN = query![realindex]["ISBN"] as! String
        
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation

    

}
